package cn.wolfcode.web.advice;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 *@ControllerAdvice  控制器功能增强注解
 * 1>在进入请求映射方法之前做功能增强, 经典用法: date日期格式化
 * 2>在进入请求映射方法之后做功能增强, 经典用法: 统一异常处理
 */
@ControllerAdvice
public class GlobalExceptionAdvice {
    //login---->抛异常(请求转发)--->handlerException
    //本质还是请求映射方法, 编写规则跟映射方法一样
    // 处理异常的方法, 方法需要贴 ExceptionHandler 注解
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException e, Model model, HandlerMethod handlerMethod,
           HttpServletRequest request, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        ResponseBody annotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if(annotation != null){
            JsonResult jsonResult = new JsonResult(false, e.getMessage());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonResult));
            return null;
        }
        model.addAttribute("errorMsg", e.getMessage());
        return "common/error";
    }
}
